package cn.lg.soar.system.biz.modules.auth.controller;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.ManyToManyDTO;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.core.annotations.DataScope;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.Id;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.database.util.MpSqlUtils;
import cn.lg.soar.database.util.PageUtils;
import cn.lg.soar.mvc.annotations.*;
import cn.lg.soar.common.enums.LogTypeEnum;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.biz.modules.auth.entity.Post;
import cn.lg.soar.system.biz.modules.auth.model.PostDto;
import cn.lg.soar.system.biz.modules.auth.model.PostQuery;
import cn.lg.soar.system.biz.modules.auth.service.IOrgService;
import cn.lg.soar.system.biz.modules.auth.service.IPostService;
import cn.lg.soar.system.biz.modules.auth.service.PostRoleRelService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;

/**
 * @author luguoxiang
 * @date 2021/8/21
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Validated
@Tag(name = "岗位(职位)")
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/post")
public class PostController extends BaseController<Post, IPostService> {

    @Override
    protected Serializable getId(Post entity) {
        return entity.getId();
    }

    @Autowired
    private IOrgService orgService;
    @Autowired
    private PostRoleRelService postRoleRelService;

    private final static String SUBJECT = "岗位(职位)";

    @Log(value = "新增" + SUBJECT, type = LogTypeEnum.CREATE)
    @IdempotentByParam("#p0")
    @RequestMapping(path = "create", method = RequestMethod.POST)
    public HttpResult<Serializable> create(@RequestBody @Validated PostDto entity) {
        return HttpResult.<Serializable>success("创建岗位(职位)成功")
                .setData(this.service.create(entity));
    }

    @Log(value = "修改" + SUBJECT, type = LogTypeEnum.UPDATE)
    @RequestMapping(path = "update", method = RequestMethod.POST)
    public HttpResult<Void> update(@RequestBody @Validated PostDto entity) {
        service.update(entity);
        return HttpResult.success();
    }

    @Log(value = "删除" + SUBJECT, type = LogTypeEnum.REMOVE)
    @RequestMapping(path = "remove", method = RequestMethod.POST)
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        return super.removeResult(ids);
    }

    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public HttpResult<PostDto> detail(@RequestParam(name = "id") @Id Long id) {
        return HttpResult.data(service.detail(id));
    }

    @DataScope(code = "post", name = "岗位")
    @RequestMapping(path = "query", method = RequestMethod.GET)
    public HttpResult<PageResult<Post>> query(PageQuery pageQuery, PostQuery query){
        QueryWrapper<Post> wrapper = new SqueryWapper<>(Post.class).listWrapper(query);
        // 根据组织机构筛选
        if (DataUtil.isValuable(query.getOrgIds())) {
            List<Long> orgIds = query.getOrgIds();
            List<Long> ids = orgService.getInferiorsIds(orgIds);
            ids.addAll(orgIds);
            wrapper.in("org_id", ids);
        }
        // 根据关联角色筛选
        MpSqlUtils.handleInOrEq(query.getRoleIds(), (sql, value) -> {
            wrapper.exists("select * from lg_sys_post_2_role r where lg_sys_post.id=r.post_id and r.role_id " + sql, value);
        });
        // 根据关联用户筛选
        MpSqlUtils.handleInOrEq(query.getUserIds(), (sql, value) -> {
            wrapper.exists("select * from lg_sys_user_2_post u where lg_sys_post.id=u.post_id and u.user_id " + sql, value);
        });
        IPage<Post> page = service.page(PageUtils.toPage(pageQuery), wrapper);
        return HttpResult.data(PageUtils.toPageResult(page));
    }

    @DataScope(code = "post", name = "岗位")
    @ListMapping
    public HttpResult<List<Post>> list(QueryParams params){
        return HttpResult.data(
                super.getList(params)
        );
    }

    @ExistMapping
    public HttpResult<Boolean> exist(QueryParams params){
        return super.existResult(params);
    }

    @DataScope(code = "post", name = "岗位")
    @Log(value = "导出" + SUBJECT, type = LogTypeEnum.EXPORT)
    @RequestMapping(path = "export", method = RequestMethod.GET)
    public void exports(QueryParams params, HttpServletResponse resp){
        super.exportExcel(PostController.SUBJECT, params, resp);
    }

    @Log(value = "导入" + SUBJECT, type = LogTypeEnum.IMPORT)
    @RequestMapping(path = "import", method = RequestMethod.POST)
    public HttpResult<Void> imports(HttpServletRequest req){
        return super.importExcel(req);
    }

    @Operation(summary = "清空缓存")
    @PostMapping(value = "clear-cache", name = "清空缓存")
    public HttpResult<Void> clearCache(){
        this.service.clearCache();
        return HttpResult.success();
    }

    @Operation(summary = "设置职位角色")
    @PostMapping(value = "set-role-ids")
    public HttpResult<Void> setRoleIds(@RequestBody @Validated ManyToManyDTO<Long, Long> dto){
        List<Long> bIds = dto.getBids();
        for (Long aId : dto.getAids()) {
            postRoleRelService.setPostRole(aId, bIds);
        }
        return HttpResult.success();
    }

    @Operation(summary = "获取职位角色id")
    @GetMapping(value = "get-role-ids")
    public HttpResult<List<Long>> getRoleIds(@RequestParam(name = "postId") Long postId){
        List<Long> ids = postRoleRelService.getRoleIds(postId);
        return HttpResult.data(ids);
    }
}
